import React, { useState, useEffect } from 'react'
import { Card, Form, Row, Col, InputNumber, Button, Tree, Space, notification } from 'antd'
import citylist from '@/common/city'
import { history, connect } from 'umi';
import FormCondition from '@/components/FormCondition';
import TableDataBlock from '@/components/TableDataBlock';
import FlxButton from '@/components/FlxButton'
import TreeModel from './components/TreeModel'
import Indentation from '@/components/Indentation';
import './index.less'
const LogisticsDetail = (props) => {
    const { dispatch } = props
    const { location } = history
    const { query = {} } = location
    const { type, detail } = query
    useEffect(() => {
        if (type === 'edit') {
            const newData = JSON.parse(detail)
            const { cityContent, cityCodeContent } = newData
            setData({
                ...newData,
                cityContent: JSON.parse(cityContent),
                cityCodeContent: JSON.parse(cityCodeContent),
            })
            form.setFieldsValue(newData)
        }
    }, [])
    const defaultList = [
        {
            label: "华东", value: 'huadong', city: [
                '上海',
                '江苏省',
                '浙江省',
                '安徽省',
                '福建省',
                '江西省',
                '山东省',
            ]
        },
        {
            label: "华中", value: 'huazhong', city: [
                '河南省',
                '湖北省',
                '湖南省',
            ]
        },
        {
            label: "华南", value: 'huanan', city: [
                '广东省',
                '广西壮族自治区',
                '海南省',
            ]
        },
        {
            label: "华北", value: 'huabei', city: [
                '北京',
                '天津',
                '河北省',
                '山西省',
                '内蒙古自治区',
            ]
        },
        {
            label: "西北", value: 'xibei', city: [
                '陕西省',
                '甘肃省',
                '青海省',
                '宁夏回族自治区',
                '新疆维吾尔自治区',
            ]
        },
        {
            label: "西南", value: 'xinan', city: [
                '重庆',
                '四川省',
                '贵州省',
                '云南省',
                '西藏自治区',
            ]
        }
    ]
    const list = defaultList.map((item => {
        const { city = [] } = item
        return {
            ...item,
            children: city.map(val => {
                return citylist.reduce((o, index) => {
                    if (index.label === val) {
                        return index
                    } else {
                        return o
                    }
                }, {})
            })
        }
    })).map((father => {
        const {
            label,
            value,
            children = []
        } = father
        return {
            label,
            value,
            pid: 0,
            children: children.map(s => {
                const { children = [] } = s
                return {
                    ...s,
                    pid: father.value,
                    children: children.map(f => {
                        return {
                            label: f.label,
                            value: f.value,
                            pid: s.value
                        }
                    })
                }
            }),
        }
    }))
    const [form] = Form.useForm()
    const [data, setData] = useState({
        cityContent: [],
        cityCodeContent: []
    })
    const [visible, setVisible] = useState(false)
    const [treeList, setRreeList] = useState(list)
    const { cityContent, cityCodeContent } = data
    function recursionGet(list, valueId) {
        let value = null;
        for (let index = 0; index < list.length; index += 1) {
            if (list[index].value === valueId) {
                value = list[index];
                break;
            }
            if (list[index].children instanceof Array && list[index].children.length > 0) {
                const text = recursionGet(list[index].children, valueId);
                if (text)
                    return text;
            }
        }
        return value;
    }
    const filterPid = (id, list = [], data) => {
        return list.reduce((item, val) => {
            if (id === val) {
                return false
            } else {
                return item
            }
        }, true)
    }
    const filterValue = (list, id) => {
        return list.reduce((item, val) => {
            if (item) {
                return item
            } else {
                if (val === id) {
                    return true
                } else {
                    return item
                }
            }
        }, false)
    }
    const containsAllChildren = (data, list) => {
        const { children = [] } = data
        const mapList = children.map((item) => { return item.value }).reduce((item, val) => {
            if (filterValue(list, val)) {
                return [...item, val]
            } else {
                return [...item]
            }
        }, [])
        if (mapList.length === children.length) {
            return true
        } else {
            return false
        }
    }
    const containsChildren = (data, list, s) => {
        const { children = [] } = data
        const mapList = children.map((item) => { return item.value }).reduce((item, val) => {
            if (filterValue(list, val)) {
                return [...item, val]
            } else {
                return [...item]
            }
        }, [])
        console.log(mapList, children, 'fatth')
        if (mapList.length === children.length) {
            return false
        } else {
            return containsAllChildren(s, list)
        }
    }
    const setDataList = (e) => {
        const { type, index } = visible
        const cityContents = e.filter(val => {
            const data = recursionGet(treeList, val)
            const { pid, children = [] } = data
            if (!filterPid(pid, e, data)) {
                const fatherData = recursionGet(treeList, pid)
                return containsChildren(fatherData, e, data)
            } else {
                if (children.length > 0) {
                    return containsAllChildren(data, e)
                }
                else {
                    return true
                }
            }

        })
        const cityCode = e
        const needData = cityContents.map(val => {
            return recursionGet(treeList, val)
        })
        if (type === 'insert') {
            setData({
                ...data,
                cityContent: [
                    ...cityContent, {
                        city: needData.map(val => {
                            return val.label
                        }).toString(),
                        cityCode: cityCode
                    }
                ],
                cityCodeContent: [
                    ...cityCodeContent, {
                        city: cityCode.filter(o => {
                            if (o.length === 4) {
                                return true
                            }
                            else {
                                return false
                            }
                        })
                    }
                ]
            })
            setVisible(false)
        }
        else {
            setData({
                ...data,
                cityContent: cityContent.map((val, key) => {
                    if (key === index) {
                        return {
                            ...val,
                            city: needData.map(val => {
                                return val.label
                            }).toString(),
                            cityCode: cityCode
                        }
                    }
                    return val
                }),
                cityCodeContent: cityCodeContent.map((val, key) => {
                    if (key === index) {
                        return {
                            ...val,
                            city: cityCode.filter(o => {
                                if (o.length === 4) {
                                    return true
                                }
                                else {
                                    return false
                                }
                            })
                        }
                    }
                    return val
                })
            })
            setVisible(false)
        }
    }
    const formItemLayout = {
        labelCol: {

        },
        wrapperCol: {

        },
    };
    const updateList = ({ index, datas }) => {
        setData({
            ...data,
            cityContent: cityContent.map((val, key) => {
                if (key === index) {
                    return {
                        ...val,
                        ...datas
                    }
                }
                else return val
            }),
            cityCodeContent: cityCodeContent.map((val, key) => {
                if (key === index) {
                    return {
                        ...val,
                        ...datas
                    }
                }
                else return val
            })
        })
    }
    const deleteList = (index) => {
        setData({
            ...data,
            cityContent: cityContent.filter((val, key) => {
                if (key === index) {
                    return false
                }
                else return true
            }),
            cityCodeContent: cityCodeContent.filter((val, key) => {
                if (key === index) {
                    return false
                }
                else return true
            })
        })
    }
    const fetchRoleEdit = () => {
        const { cityContent, cityCodeContent } = data
        form.validateFields().then(async (values) => {
            const { expressPriceType } = values
            let flag = cityCodeContent.reduce((item, val) => {
                if (expressPriceType === 'weight') {
                    if (!val.firstValue || !val.firstPrice || !val.nextValue || !val.nextPrice) {
                        return false
                    }
                    return item
                }
                else {
                    if (!val.firstValue || (!val.firstPrice && val.firstPrice !== 0) || !val.nextValue || (!val.nextPrice && val.nextPrice !== 0)) {
                        return false
                    }
                    return item
                }

            }, true)
            if (!flag) {
                return notification.warning({
                    message: '错误提示',
                    description: '请填写完信息后提交',
                });
            }
            if (type === 'edit') {
                const { templateSource, id } = data
                dispatch({
                    type: 'expressTemplate/fakeSaveExpressTemplate',
                    payload: {
                        ...data,
                        ...values,
                        id: templateSource === 'system' ? '' : id,
                        cityContent: JSON.stringify(cityContent),
                        cityCodeContent: JSON.stringify(cityCodeContent),
                    },
                    callback: () => {
                        history.goBack();
                    },
                });
            }
            else {
                dispatch({
                    type: 'expressTemplate/fakeSaveExpressTemplate',
                    payload: {
                        ...values,
                        ...data,
                        cityContent: JSON.stringify(cityContent),
                        cityCodeContent: JSON.stringify(cityCodeContent),
                    },
                    callback: () => {
                        history.goBack();
                    },
                });
            }

        }
        );

    };
    const formItems = [
        {
            label: '模版名称',
            name: 'templateName',
        },
        {
            label: '计费方式',
            name: 'expressPriceType',
            type: 'radio',
            select: {
                piece: '按件',
                weight: '重量',
            }
        },
    ]
    const getColumns = [
        {
            title: '可配送区域',
            dataIndex: 'city',
            render: (e, record, index) => {
                const { cityCode } = record
                console.log(e, 111111111111)
                return <Space>
                    <Indentation width={200} str={e}></Indentation>
                    <Button onClick={() => deleteList(index)} type='link'>删除</Button>
                    <Button onClick={() => setVisible({
                        index: index,
                        type: 'edit',
                        show: true,
                        detail: cityCode,
                        disabledList: filterDesabledList(index)
                    })} type='link'>编辑</Button>
                </Space>
            }
        },
        {
            title: '首件',
            dataIndex: 'firstValue',
            render: (val, record, index) => {
                return <InputNumber value={val} onChange={(e) => {
                    updateList({
                        index,
                        datas: { firstValue: e }
                    })
                }}></InputNumber>
            }
        },
        {
            title: '运费',
            dataIndex: 'firstPrice',
            render: (val, record, index) => {
                return <InputNumber value={val} onChange={(e) => {
                    updateList({
                        index,
                        datas: { firstPrice: e }

                    })
                }}></InputNumber>
            }
        },
        {
            title: '续件',
            dataIndex: 'nextValue',
            render: (val, record, index) => {
                return <InputNumber value={val} onChange={(e) => {
                    updateList({
                        index,
                        datas: { nextValue: e }
                    })
                }}></InputNumber>
            }
        },
        {
            title: '续费',
            dataIndex: 'nextPrice',
            render: (val, record, index) => {
                return <InputNumber value={val} onChange={(e) => {
                    updateList({
                        index,
                        datas: {
                            nextPrice: e
                        }

                    })
                }}></InputNumber>
            }
        },

    ]
    const filterDesabledList = (index) => {
        if (index || index === 0) {
            return cityContent.reduce((item, val, o) => {
                if (index === o) {
                    console.log(index, o, 'filterIndex')
                    return item
                } else {
                    const { cityCode } = val
                    return [...item, ...cityCode]
                }
            }, [])
        } else {
            return cityContent.reduce((item, val, o) => {
                const { cityCode } = val
                return [...item, ...cityCode]
            }, [])
        }

    }
    return <Card title='设置物流模板'>
        <Row>
            <Col span={18}>
                <FormCondition
                    formItemLayouts={formItemLayout}
                    form={form}
                    formItems={formItems}
                    initialValues={{}}
                ></FormCondition>
            </Col>
            <Col span={6}>
            </Col>
            <Col span={24}>
                <TableDataBlock
                    pagination={false}
                    columns={getColumns}
                    list={cityContent}
                    rowKey={(record) => `${record.id}`}
                ></TableDataBlock>
            </Col>
            <Col span={24}>
                <Button style={{ marginTop: 24 }} onClick={() => {
                    setVisible({
                        show: true,
                        type: 'insert',
                        disabledList: filterDesabledList()
                    })
                }} type='primary'>
                    添加可配送区域
                </Button>
            </Col>
            <TreeModel handleCallback={(e) => setDataList(e)} treeList={treeList} visible={visible} onClose={() => { setVisible(false) }}></TreeModel>
            <FlxButton onOk={() => fetchRoleEdit()}></FlxButton>
        </Row>
    </Card>
}

export default connect(({ system, loading, information }) => ({
    ...system,
    loading: loading.models.system || loading.effects['setting/fakeExportAdminStageData'],
}))(LogisticsDetail);
